package org.example.volunteersystem.controller;

import org.example.volunteersystem.dto.LoginDTO;
import org.example.volunteersystem.entity.User;
import org.example.volunteersystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginDTO loginDTO, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        // 从 Session 获取正确验证码
        String correctCaptcha = (String) request.getSession().getAttribute("captcha");

        // 验证验证码
        if (correctCaptcha == null || !correctCaptcha.equalsIgnoreCase(loginDTO.getCaptcha())) {
            result.put("code", 400);
            result.put("msg", "验证码错误或已过期");
            return result;
        }

        // 验证用户名密码
        User u = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        if (u != null) {
            result.put("code", 200);
            result.put("msg", "登录成功");
            result.put("data", u);
        } else {
            result.put("code", 401);
            result.put("msg", "用户名或密码错误");
        }
        return result;
    }


    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        int r = userService.register(user);
        Map<String, Object> result = new HashMap<>();

        if (r == -1) {
            result.put("code", 400);
            result.put("msg", "用户名已存在，请更换用户名");
        } else if (r > 0) {
            result.put("code", 200);
            result.put("msg", "注册成功");
        } else {
            result.put("code", 500);
            result.put("msg", "注册失败");
        }
        return result;
    }
}

